package core

import (
	"strings"

	"gitee.com/minph/siphan/diycode"
	"gitee.com/minph/siphan/exception"
)

// 加密结果
type EncryptResult struct {
	// 密钥
	Key string
	// 密文
	Val string

	CodeSlice
}

func EncryptFromSlice(text string, codeSlice CodeSlice) (*EncryptResult, error) {
	var val string
	parsedText := diycode.EncodeTextByUnicode(text)

	for i, char := range strings.Split(parsedText, "") {
		target, err := codeSlice.FindChar(char)
		if err != nil {
			return nil, exception.ErrCharNotFound{Char: char}
		}

		index := (i + target.Index) % len(codeSlice)
		target, err = codeSlice.FindIndex(index)
		if err != nil {
			return nil, exception.ErrIndexNotFound{Index: index}
		}
		val += target.Char

	}

	res := &EncryptResult{
		Val:       val,
		CodeSlice: codeSlice,
		Key:       codeSlice.GenStr(),
	}

	return res, nil
}

// 加密
func Encrypt(text string) (*EncryptResult, error) {

	codeSlice, _ := diycode.GetRandCodeSlice()
	return EncryptFromSlice(text, codeSlice)
}
